package com.jiubanqingchen.wish.framework.context.locale;

import java.util.Locale;

/**
 * @author light_dust
 * @since 2021/5/26 10:42
 */
public abstract class LocaleContextHolder {
    private static final ThreadLocal<LocaleContext> localeContextHolder = new ThreadLocal<>();

    public static void resetLocaleContext() {
        localeContextHolder.remove();
    }

    public static void setLocaleContext(LocaleContext localeContext, boolean inheritable) {
        if (localeContext == null) {
            resetLocaleContext();
        } else {
            if (inheritable) {
                localeContextHolder.remove();
            } else {
                localeContextHolder.set(localeContext);
            }
        }
    }

    public static LocaleContext getLocaleContext() {
        return localeContextHolder.get();
    }

    public static void setLocaleContext(LocaleContext localeContext) {
        setLocaleContext(localeContext, false);
    }

    public static void setLocale(Locale locale, boolean inheritable) {
        LocaleContext localeContext;
        if (locale != null) {
            localeContext = new SimpleLocaleContext(locale);
        } else {
            localeContext = null;
        }
        setLocaleContext(localeContext, inheritable);
    }

    public static Locale getLocale() {
        return getLocale(getLocaleContext());
    }

    public static void setLocale(Locale locale) {
        setLocale(locale, false);
    }

    public static Locale getLocale(LocaleContext localeContext) {
        if (localeContext != null) {
            Locale locale = localeContext.getLocale();
            if (locale != null) {
                return locale;
            }
        }
        return Locale.getDefault();
    }
}
